#include "stdafx.h"

#include <QTcpSocket>
#include <QHostAddress>
#include <QFileDialog>

#include "binarysenderwindow.h"

BinarySenderWindow::BinarySenderWindow(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);
    tcpSocket = new QTcpSocket;
}

BinarySenderWindow::~BinarySenderWindow()
{

}

void BinarySenderWindow::on_connectButton_clicked()
{
    auto hoststr = ui.hostEdit->text();
    QString hostname;
    int port;

    if (hoststr.indexOf(':') != -1)
    {
        hostname = hoststr.left(hoststr.indexOf(':'));
        port = hoststr.right(hoststr.length() - hoststr.indexOf(':') + 1).toInt();
    }
    else
    {
        hostname = hoststr;
        port = 80;
    }
   
    tcpSocket->connectToHost(hostname, port);

    connect(tcpSocket, &QTcpSocket::connected, []()
    {
        ;
    });

    connect(tcpSocket, &QTcpSocket::readyRead, this, &BinarySenderWindow::on_readRead);
}

void BinarySenderWindow::on_sendButton_clicked()
{
    QString text = ui.commandEdit->toPlainText();
    tcpSocket->write(text.toLocal8Bit());
}

void BinarySenderWindow::on_sendFileButton_clicked()
{
    auto fileName = QFileDialog::getOpenFileName(this, tr("Open Image"));

    QFile f(fileName);
    f.open(QIODevice::ReadOnly);
    if (f.isOpen())
    {
        auto data = f.readAll();
        tcpSocket->write(data);
    }
}

void BinarySenderWindow::on_sendReturnButton_clicked()
{
    tcpSocket->write("\n");
    tcpSocket->flush();
}

void BinarySenderWindow::on_readRead()
{
    QByteArray data = tcpSocket->readAll();
    ui.dataEdit->append(data);
}
